package kbpost

import (
	"context"
	"fmt"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/blog/model"
	"mall/service/blog/rpc/internal/svc"
	"mall/service/blog/rpc/internal/utils/errorhandler"
	"mall/service/blog/rpc/types/blog"

	"github.com/gosimple/slug"
	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateKBPostLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateKBPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateKBPostLogic {
	return &UpdateKBPostLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateKBPostLogic) UpdateKBPost(in *blog.KBPostInfo) (*blog.BaseResp, error) {
	logx.Infof("UpdatePost : %+v ", in)

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(in.Ids) > 0 && in.Status != nil { // 批量修改状态
		now := time.Now()
		for _, id := range in.Ids {
			if id > 0 {
				post, err := l.svcCtx.KBEntry.FindOneNoCache(l.ctx, tx, id)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}

				if *in.Status == uint32(globalkey.PostStatusSticky) {
					post.StickyType = 2
				} else if *in.Status == uint32(globalkey.PostStatusUnSticky) {
					post.StickyType = 0
				} else {
					post.PostStatus = uint16(*in.Status)
				}
				post.PostModifiedDate = now
				err = l.svcCtx.KBEntry.Update(l.ctx, tx, post, nil)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}
			}
		}

		tx.Commit()

		return &blog.BaseResp{
			Msg: i18n.UpdateSuccess,
		}, nil
	}

	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	if in.Title != nil && len(strings.TrimSpace(*in.Title)) == 0 {
		return nil, errorx.NewInvalidArgumentError("cms.postTitleRequired")
	}

	id := *in.Id
	entry, err := l.svcCtx.KBEntry.FindOneNoCache(l.ctx, tx, id)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	entrySectionId := entry.SectionID
	if (in.Title != nil && entry.PostTitle != strings.TrimSpace(*in.Title)) || (in.Slug != nil && entry.PostName != strings.TrimSpace(*in.Slug)) { // title或slug改变了
		if entry.PostParentID == 0 { // 是基础词条
			filterMap := make(map[string]map[string][]any)
			filterMap[model.BlogKnowledgeBasisColumns.SectionID] = map[string][]any{
				"equalTo": {entrySectionId},
			}
			filterMap[model.BlogKnowledgeBasisColumns.PostParentID] = map[string][]any{
				"equalTo": {0},
			}
			if in.Title != nil {
				filterMap[model.BlogKnowledgeBasisColumns.PostTitle] = map[string][]any{
					"equalTo": {strings.TrimSpace(*in.Title)},
				}
			} else {
				filterMap[model.BlogKnowledgeBasisColumns.PostTitle] = map[string][]any{
					"equalTo": {entry.PostTitle},
				}
			}
			if in.Slug != nil && len(strings.TrimSpace(*in.Slug)) > 0 {
				filterMap[model.BlogKnowledgeBasisColumns.PostName] = map[string][]any{
					"equalTo": {strings.TrimSpace(*in.Slug)},
				}
			} else {
				filterMap[model.BlogKnowledgeBasisColumns.PostName] = map[string][]any{
					"equalTo": {entry.PostName},
				}
			}
			list, _, err := l.svcCtx.KBEntry.GetList(l.ctx, model.M{
				"pageSize": uint64(2),
				"select":   ",",
			}, -1, filterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if len(list) > 1 {
				return nil, errorx.NewInvalidArgumentError("cms.entryAlreadyExists")
			}

			if len(list) == 1 && list[0].ID != id {
				return nil, errorx.NewInvalidArgumentError("cms.entryAlreadyExists")
			}

			// if len(list) > 0 { // 继续判断词条类型
			// 	var eids []any
			// 	for _, v := range list {
			// 		eids = append(eids, v.ID)
			// 	}

			// 	termFilterMap := make(map[string]map[string][]any)
			// 	termFilterMap[model.BlogTermRelationshipColumns.ObjectID] = map[string][]any{
			// 		"in": eids,
			// 	}
			// 	termFilterMap[model.BlogTermRelationshipColumns.ObjectType] = map[string][]any{
			// 		"equalTo": {globalkey.PostTypeKnowledgeBase},
			// 	}
			// 	termFilterMap[model.BlogTermRelationshipColumns.TermID] = map[string][]any{
			// 		"equalTo": {entrySectionId},
			// 	}
			// 	relationshipList, _, err := l.svcCtx.Term.GetRelationshipList(l.ctx, model.M{
			// 		"pageSize": uint64(10),
			// 		"select":   model.BlogTermRelationshipColumns.ObjectID,
			// 	}, -1, termFilterMap)
			// 	if err != nil {
			// 		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			// 	}

			// 	if len(relationshipList) > 1 {
			// 		return nil, errorx.NewInvalidArgumentError("cms.entryAlreadyExists")
			// 	}

			// 	if relationshipList[0].ObjectID != id {
			// 		return nil, errorx.NewInvalidArgumentError("cms.entryAlreadyExists")
			// 	}
			// }
		}
	}

	var skipMeta bool
	if in.SkipMeta != nil && *in.SkipMeta > 0 {
		skipMeta = true
	}
	var skipMedia bool
	if in.SkipMedia != nil && *in.SkipMedia > 0 {
		skipMedia = true
	}
	var skipCategory bool
	if in.SkipCategory != nil && *in.SkipCategory > 0 {
		skipCategory = true
	}
	var skipTag bool
	if in.SkipTag != nil && *in.SkipTag > 0 {
		skipTag = true
	}
	var skipRelation bool
	if in.SkipRelation != nil && *in.SkipRelation > 0 {
		skipRelation = true
	}
	var skipContent bool
	if in.SkipContent != nil && *in.SkipContent > 0 {
		skipContent = true
	}

	if in.Title != nil {
		entry.PostTitle = strings.TrimSpace(*in.Title)
	}
	if in.Slug != nil {
		entry.PostName = strings.TrimSpace(*in.Slug)
	}
	if in.Excerpt != nil {
		entry.PostExcerpt = strings.TrimSpace(*in.Excerpt)
	}

	var visibility uint32
	if in.Visibility != nil && *in.Visibility > 0 {
		visibility = *in.Visibility
	}

	var publicDate time.Time
	var isFuturePublicDate bool
	if in.PublicDate != nil && len(*in.PublicDate) > 0 {
		if localTime, err := modelx.ParseLocalTime(*in.PublicDate); err == nil {
			publicDate = localTime
			isFuturePublicDate = true
		}
	}

	var status uint16
	var futureStatus int32  // 未来发布后的状态
	var pendingStatus int32 // 审核后的状态
	if in.Status != nil {
		if *in.Status == uint32(globalkey.PostStatusPublish) { // 发布
			if isFuturePublicDate { // 未来发布
				status = uint16(globalkey.PostStatusFuture)        // 暂为future状态
				if visibility == globalkey.PostVisibilityPrivate { // 未来发布后为private，否则为public
					futureStatus = globalkey.PostStatusPrivate
				} else {
					futureStatus = globalkey.PostStatusPublish
				}
			} else { // 立即发布
				if visibility == globalkey.PostVisibilityPrivate {
					status = uint16(globalkey.PostStatusPrivate)
				} else {
					status = uint16(globalkey.PostStatusPublish)
				}
			}
		} else { // 其他状态
			status = uint16(*in.Status)
			if isFuturePublicDate { // 未来发布
				pendingStatus = globalkey.PostStatusFuture         // 审核后为future状态
				if visibility == globalkey.PostVisibilityPrivate { // 审核且未来发布后为private，否则为public
					futureStatus = globalkey.PostStatusPrivate
				} else {
					futureStatus = globalkey.PostStatusPublish
				}
			} else { // 立即发布
				if visibility == globalkey.PostVisibilityPrivate {
					pendingStatus = globalkey.PostStatusPrivate
				} else {
					pendingStatus = globalkey.PostStatusPublish
				}
			}
		}
		entry.PostStatus = status
	}

	if in.CommentStatus != nil {
		if *in.CommentStatus > 0 {
			entry.CommentStatus = 1
		} else {
			entry.CommentStatus = 0
		}
	}
	if in.Sort != nil {
		entry.MenuOrder = int(*in.Sort)
	}
	entry.PostModifiedDate = time.Now()

	if visibility == globalkey.PostVisibilityPasswordProtected && in.Password != nil {
		entry.PostPassword = strings.TrimSpace(*in.Password)
	}
	if isFuturePublicDate {
		entry.PostDate = publicDate
	}
	// var sticky string
	if in.Sticky != nil && *in.Sticky > 0 {
		entry.StickyType = uint8(*in.Sticky)
		// switch int32(*in.Sticky) {
		// case globalkey.BlogStickyTypeCategory:
		// 	sticky = "category"
		// case globalkey.BlogStickyTypeTag:
		// 	sticky = "tag"
		// default:
		// 	sticky = "frontpage"
		// }
	}

	rel := &model.KBEntryRel{}
	if !skipContent {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.BlogKnowledgeBaseDetailColumns.KnowledgeBaseID] = map[string][]any{
			"equalTo": {id},
		}
		list, _, err := l.svcCtx.KBEntry.GetDetailList(l.ctx, model.M{
			"pageSize": uint64(1),
			"orderBy":  model.BlogKnowledgeBaseDetailColumns.DetailID + " DESC",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 {
			rel.Detail = list[0]
			if in.Content != nil {
				rel.Detail.PostContent = *in.Content
			}
			if in.ContentFiltered != nil {
				rel.Detail.PostContentFiltered = *in.ContentFiltered
			}
		}
	}

	var thumbnailIdMetaId uint64
	var thumbnailUrlMetaId uint64
	var photoCountMetaId uint64
	var futureStatusMetaId uint64
	var pendingStatusMetaId uint64
	// var viewCountMetaId uint64
	// var commentCountMetaId uint64
	// var forwardCountMetaId uint64
	// var stickyMetaId uint64
	if !skipMeta {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.BlogKnowledgeBaseMetumColumns.KnowledgeBaseID] = map[string][]any{
			"equalTo": {id},
		}
		list, _, err := l.svcCtx.KBEntry.GetMeta(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 { // 原有的 Meta（决定现有的是增还是改）
			var omids []uint64
			omidMap := make(map[uint64]struct{})
			for _, v := range list {
				if len(v.MetaKey) > 0 && v.MetaValue.Valid {
					switch v.MetaKey { // 先排除特殊Key
					case "_thumbnail_id":
						thumbnailIdMetaId = v.MetaID
					case "_thumbnail_url":
						thumbnailUrlMetaId = v.MetaID
					case "_photo_count":
						photoCountMetaId = v.MetaID
					case "_future_status":
						futureStatusMetaId = v.MetaID
					case "_pending_status":
						pendingStatusMetaId = v.MetaID
					case "_view_count":
						// viewCountMetaId = v.MetaID
					case "_comment_count":
						// commentCountMetaId = v.MetaID
					case "_forward_count":
						// forwardCountMetaId = v.MetaID
					case "_perfume_count", "_product_count", "_sku_count", "_min_product_gems":
					case "_rating_count", "_average_rating", "_base_rating", "_base_rating_weight", "_like_count":
					case "_season", "_popularity", "_background_color", "_font_color_light", "_sticky":
					// case "_year", "_gender":
					// case "_sticky":
					// 	stickyMetaId = v.MetaID
					default:
						omids = append(omids, v.MetaID)
						omidMap[v.MetaID] = struct{}{}
					}
				}
			}

			// 现有的 Meta（决定原有的是删还是留）
			nmidMap := make(map[uint64]struct{})
			if len(in.Meta) > 0 {
				for _, v := range in.Meta {
					if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
						continue
					}

					if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
						continue
					}

					var metum model.BlogKnowledgeBaseMetum
					metum.KnowledgeBaseID = id
					metum.MetaKey = strings.TrimSpace(*v.Key)
					metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))

					if v.Id != nil && *v.Id > 0 {
						if _, ok := omidMap[*v.Id]; ok { // 有值且是有效值，为修改，否则为新增
							nmidMap[*v.Id] = struct{}{}
							metum.MetaID = *v.Id
						}
					}

					rel.Meta = append(rel.Meta, &metum)
				}
			}

			for _, mid := range omids {
				if _, ok := nmidMap[mid]; !ok { // 当前不存在的值，应该删除
					rel.DelMetaIds = append(rel.DelMetaIds, mid)
				}
			}
		} else if len(in.Meta) > 0 { // 不存在原值，则都是新增
			for _, v := range in.Meta {
				if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
					continue
				}

				if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
					continue
				}

				var metum model.BlogKnowledgeBaseMetum
				metum.KnowledgeBaseID = id
				metum.MetaKey = strings.TrimSpace(*v.Key)
				metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))

				rel.Meta = append(rel.Meta, &metum)
			}
		}
	}
	// if len(sticky) > 0 {
	// 	rel.Meta = append(rel.Meta, &model.BlogKnowledgeBaseMetum{
	// 		MetaID:          stickyMetaId,
	// 		KnowledgeBaseID: id,
	// 		MetaKey:         "_sticky",
	// 		MetaValue:       null.StringFrom(sticky),
	// 	})
	// }
	if futureStatus > 0 {
		rel.Meta = append(rel.Meta, &model.BlogKnowledgeBaseMetum{
			MetaID:          futureStatusMetaId,
			KnowledgeBaseID: id,
			MetaKey:         "_future_status",
			MetaValue:       null.StringFrom(strconv.FormatInt(int64(futureStatus), 10)),
		})
	}
	if pendingStatus > 0 {
		rel.Meta = append(rel.Meta, &model.BlogKnowledgeBaseMetum{
			MetaID:          pendingStatusMetaId,
			KnowledgeBaseID: id,
			MetaKey:         "_pending_status",
			MetaValue:       null.StringFrom(strconv.FormatInt(int64(pendingStatus), 10)),
		})
	}

	if !skipMedia {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.BlogAttachmentRelationshipColumns.ObjectID] = map[string][]any{
			"equalTo": {id},
		}
		filterMap[model.BlogAttachmentRelationshipColumns.ObjectType] = map[string][]any{
			"equalTo": {globalkey.AttachmentLogTypeKnowledgeBase},
		}
		list, _, err := l.svcCtx.KBEntry.GetMedia(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		mediaUidMap := make(map[uint64]*model.BlogAttachmentRelationship)
		if len(list) > 0 {
			for _, v := range list {
				mediaUidMap[v.AttachmentRelationshipID] = v
			}
		}

		allMediaMap := make(map[string]string)
		exclusiveMap := make(map[string]string) // 防删除原有图文中的图片
		if len(in.AllMedia) > 0 {
			for _, v := range in.AllMedia {
				if v.Id != nil && v.Url != nil && len(*v.Id) > 0 && len(*v.Url) > 0 {
					allMediaMap[*v.Id] = *v.Url
					exclusiveMap[*v.Url] = *v.Id
				}
			}
		}

		if len(in.NewMedia) > 0 {
			var thumbnailOrder uint
			var thumbnailId uint64
			var thumbnailUrl string
			for idx, v := range in.NewMedia {
				var url string
				if v.Url != nil && len(*v.Url) > 0 { // v.Uri  content版本（包含?id）  v.Url  url当前版本 | attachment当前版本
					url = *v.Url
				}
				if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
					url = *v.Uri
				}
				if len(url) == 0 {
					continue
				}

				var thumbnail uint8
				if v.Thumbnail != nil && *v.Thumbnail > 0 {
					thumbnail = uint8(*v.Thumbnail)
				}
				var order uint
				if v.Order != nil {
					order = uint(*v.Order)
				} else {
					order = uint(idx) + globalkey.AttachmentOrderOffset
				}
				var altText string
				if v.AltText != nil && len(*v.AltText) > 0 {
					altText = *v.AltText
				}
				var meta []string
				if v.Name != nil && len(*v.Name) > 0 {
					meta = append(meta, "filename:"+*v.Name)
					if len(altText) == 0 {
						altText = *v.Name
					}
				}
				if v.MetaData != nil && len(*v.MetaData) > 0 {
					meta = append(meta, *v.MetaData)
				}
				if v.MimeType != nil && len(*v.MimeType) > 0 {
					meta = append(meta, "mimeType:"+*v.MimeType)
				}
				metaData := strings.Join(meta, ";")

				var mediaId uint64
				if v.Id != nil && len(*v.Id) > 0 {
					if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil {
						mediaId = uint64(i)
					}
				}
				var uid uint64
				if v.Uid != nil && *v.Uid > 0 {
					uid = *v.Uid
				}

				if uid > 0 { // 原有缩略图
					if _, ok := mediaUidMap[uid]; ok { // 存在，修改，否则无效
						delete(mediaUidMap, uid)
						rel.Media = append(rel.Media, &model.BlogAttachmentRelationship{
							AttachmentRelationshipID: uid,
							AttachmentID:             mediaId,
							AttachmentThumbnail:      thumbnail,
							AttachmentOrder:          order,
							AttachmentImageURL:       url,
							AttachmentImageAlt:       altText,
							AttachmentImageMeta:      metaData,
						})
					}
					continue
				}

				media := &model.BlogAttachmentRelationship{
					AttachmentID:        mediaId,
					AttachmentThumbnail: thumbnail,
					AttachmentOrder:     order,
					AttachmentImageURL:  url,
					AttachmentImageAlt:  altText,
					AttachmentImageMeta: metaData,
				}

				if thumbnail == 0 && mediaId > 0 { // thumbnail == 0 不是缩略图， mediaId > 0 不是外链，获取图文uri
					if uri, ok := allMediaMap[*v.Id]; ok {
						media.AttachmentSource = uri
					}
				}

				rel.Media = append(rel.Media, media)
			}

			for _, v := range rel.Media {
				if v.AttachmentThumbnail > 0 && (len(thumbnailUrl) == 0 || thumbnailOrder > v.AttachmentOrder) { // thumbnailOrder尚未赋值，或当前值更小
					thumbnailOrder = v.AttachmentOrder
					thumbnailId = v.AttachmentID
					thumbnailUrl = v.AttachmentImageURL
				}
			}

			if len(thumbnailUrl) > 0 {
				rel.Meta = append(rel.Meta, &model.BlogKnowledgeBaseMetum{
					MetaID:    thumbnailIdMetaId,
					MetaKey:   "_thumbnail_id",
					MetaValue: null.StringFrom(strconv.FormatInt(int64(thumbnailId), 10)),
				})
				rel.Meta = append(rel.Meta, &model.BlogKnowledgeBaseMetum{
					MetaID:    thumbnailUrlMetaId,
					MetaKey:   "_thumbnail_url",
					MetaValue: null.StringFrom(thumbnailUrl),
				})
			}
			rel.Meta = append(rel.Meta, &model.BlogKnowledgeBaseMetum{
				MetaID:    photoCountMetaId,
				MetaKey:   "_photo_count",
				MetaValue: null.StringFrom(strconv.FormatInt(int64(len(rel.Media)), 10)),
			})
		}

		for _, v := range mediaUidMap {
			if _, ok := exclusiveMap[v.AttachmentSource]; ok { // 如果在图文中，保留一次
				delete(exclusiveMap, v.AttachmentSource)
				continue
			}

			rel.DelMediaIds = append(rel.DelMediaIds, v.AttachmentRelationshipID)
		}
	}

	if !skipCategory || !skipTag {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.BlogTermRelationshipColumns.ObjectID] = map[string][]any{
			"equalTo": {id},
		}
		filterMap[model.BlogTermRelationshipColumns.ObjectType] = map[string][]any{
			"equalTo": {globalkey.PostTypeKnowledgeBase},
		}
		list, _, err := l.svcCtx.Term.GetRelationshipList(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 { // 原有的 Tags（决定现有的是增还是改）
			var tids []any
			oridMap := make(map[uint64]uint64)
			for _, v := range list {
				tids = append(tids, v.TermID)
				oridMap[v.TermID] = v.TermRelationshipID
			}

			termFilterMap := make(map[string]map[string][]any)
			termFilterMap[model.BlogTermColumns.TermID] = map[string][]any{
				"in": tids,
			}
			terms, _, err := l.svcCtx.Term.GetList(l.ctx, model.M{}, -1, termFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			ocidMap := make(map[uint64]struct{})
			otidMap := make(map[uint64]struct{})
			if len(terms) > 0 {
				for _, v := range terms {
					switch int32(v.Taxonomy) {
					case globalkey.TermTaxonomyCategory: // 是分类
						ocidMap[v.TermID] = struct{}{}
					case globalkey.TermTaxonomyTag: // 是标签
						otidMap[v.TermID] = struct{}{}
					}
				}
			}

			ntidMap := make(map[uint64]struct{})
			// 现有的 CategoryIds（决定原有的是删还是留）
			if !skipCategory && len(in.CategoryIds) > 0 {
				for _, tid := range in.CategoryIds {
					ntidMap[tid] = struct{}{}

					if _, ok := ocidMap[tid]; ok { // 已有，不新增
						continue
					}

					rel.CategoryIds = append(rel.CategoryIds, tid)
				}
			}

			// 现有的 TagIds（决定原有的是删还是留）
			if !skipTag && len(in.TagIds) > 0 {
				for _, tid := range in.TagIds {
					ntidMap[tid] = struct{}{}

					if _, ok := otidMap[tid]; ok { // 已有，不新增
						continue
					}

					rel.TagIds = append(rel.TagIds, tid)
				}
			}

			if !skipCategory {
				for cid := range ocidMap {
					if _, ok := ntidMap[cid]; !ok { // 当前不存在的值，应该删除
						if rid, ok := oridMap[cid]; ok {
							rel.DelTermIds = append(rel.DelTermIds, rid)
						}
					}
				}
			}
			if !skipTag {
				for tid := range otidMap {
					if _, ok := ntidMap[tid]; !ok { // 当前不存在的值，应该删除
						if rid, ok := oridMap[tid]; ok {
							rel.DelTermIds = append(rel.DelTermIds, rid)
						}
					}
				}
			}
		} else {
			if len(in.CategoryIds) > 0 { // 不存在原值，则都是新增
				rel.CategoryIds = in.CategoryIds
			}
			if len(in.TagIds) > 0 { // 不存在原值，则都是新增
				rel.TagIds = in.TagIds
			}
		}
	}

	if !skipRelation {
		relationEntityName := model.RpcEntityNames.BlogBookRelation
		if settingMap, ok := model.RpcEntityPreloadMap[relationEntityName]; ok {
			var uriTemplate string                // 当前词条 uri 模板
			var parentSectionId uint64            // 当前父级词条类型Section ID（当前为香水词条则为品牌词条类型ID）
			sectionMap := make(map[string]uint64) // 词条类型map 'Slug' => 'Id'
			groupMap := make(map[string]uint)     // 词条类型map 'Slug' => 'Group'
			var parentEntryId uint64              // 当前香水词条perfumes 的 parentId 为 品牌词条brands 的 Id
			var parentEntrySlug string
			for _, v := range settingMap {
				if v.Id > 0 {
					if v.Id == entrySectionId {
						uriTemplate = v.UriTemplate
						if v.ParentId > 0 {
							parentSectionId = v.ParentId
						}
					}
					sectionMap[v.Slug] = v.Id
				}
				if v.Group > 0 {
					groupMap[v.Slug] = v.Group
				}
			}

			filterMap := make(map[string]map[string][]any)
			filterMap[model.BlogKnowledgeBaseRelationshipColumns.FromEntryID] = map[string][]any{
				"equalTo": {id},
			}
			list, _, err := l.svcCtx.KBEntry.GetRelationshipList(l.ctx, model.M{}, -1, filterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			relationMap := make(map[int64]*model.BlogKnowledgeBaseRelationship)
			if len(list) > 0 { // 原有的 Relationship（决定现有的是增还是改）
				for _, v := range list {
					relationMap[int64(v.ToEntryID)] = v
				}
			}

			if in.RelationIds != nil && len(*in.RelationIds) > 0 {
				pairs := strings.Split(*in.RelationIds, ";")
				if len(pairs) > 0 {
					for _, pair := range pairs {
						parts := strings.Split(pair, ":")
						if len(parts) == 2 && len(parts[0]) > 0 && len(parts[1]) > 0 {
							section := parts[0]
							values := strings.Split(parts[1], ",")
							if len(values) > 0 {
								var sectionId uint64
								var groupId uint
								if setting, ok := settingMap[section]; ok { // 按slug简写查找
									sectionId = setting.Id
									groupId = setting.Group
								} else { // 前调、中调、后调、版本
									if settingId, ok := sectionMap[section]; ok { // 按slug查找
										sectionId = settingId
									}
									if gid, ok := groupMap[section]; ok {
										groupId = gid
									}
								}
								if sectionId > 0 {
									for idx, value := range values {
										if i, err := strconv.ParseInt(value, 10, 64); err == nil {
											if r, ok := relationMap[i]; ok {
												delete(relationMap, i) // 排除掉不需要删除的项

												rel.Relations = append(rel.Relations, &model.BlogKnowledgeBaseRelationship{
													EntryRelationshipID: r.EntryRelationshipID,
													FromSectionID:       entrySectionId,
													ToEntryID:           uint64(i),
													ToSectionID:         sectionId,
													ToEntryGroup:        groupId,
													ToEntryOrder:        uint(idx),
													ToEntryMeta:         section,
												})
											} else {
												rel.Relations = append(rel.Relations, &model.BlogKnowledgeBaseRelationship{
													FromSectionID: entrySectionId,
													ToEntryID:     uint64(i),
													ToSectionID:   sectionId,
													ToEntryGroup:  groupId,
													ToEntryOrder:  uint(idx),
													ToEntryMeta:   section,
												})
											}

											if parentSectionId == 0 || parentEntryId > 0 { // 不是香水词条或者已找到品牌词条id
												continue
											}

											if sectionId == parentSectionId {
												parentEntryId = uint64(i)
											}
										}
									}
								}
							}
						}
					}
				}

				for _, r := range relationMap {
					rel.DelRelationIds = append(rel.DelRelationIds, r.EntryRelationshipID)
				}
			}

			if parentEntryId > 0 {
				parent, err := l.svcCtx.KBEntry.FindOneNoCache(l.ctx, nil, parentEntryId)
				if err != nil {
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}

				if len(parent.PostName) > 0 {
					parentEntrySlug = fmt.Sprintf("%s/", slug.Make(parent.PostName))
				}
			}

			if len(uriTemplate) > 0 {
				slug.Lowercase = false

				entry.GUID = fmt.Sprintf("%s%s%s/", uriTemplate, parentEntrySlug, slug.Make(entry.PostName))
			}
		}
	}

	err = l.svcCtx.KBEntry.Update(l.ctx, tx, entry, rel)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &blog.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
